package B刷题.A栈和队列;

import java.util.Stack;

/**
 * @author wei.zhao
 * @description: 程序员代码面试指南：如何仅用递归函数和栈操作逆序一个栈
 * @date 2022/12/2 16:09
 */
public class Code04_ReverseStackUsingRecursive {

    public static void reverse(Stack<Integer> stack) {
        if (stack.isEmpty()) {
            return;
        }
        int last = getAndRemoveLastElement(stack);
        reverse(stack);
        stack.add(last);
    }

    /**
     * 获取并移除栈底元素
     */
    public static int getAndRemoveLastElement(Stack<Integer> stack) {
        Integer pop = stack.pop();
        if (stack.isEmpty()) {
            return pop;
        } else {
            int lastElement = getAndRemoveLastElement(stack);
            stack.add(pop);
            return lastElement;
        }
    }

}
